package com.heimo.agentlicence.htmlchecker;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;

import com.heimo.agentlicence.model.AgentRecord;

public class LicenceResultChecker extends BasicChecker {
	private final String TAG = "LicenceResultChecker";

	public List<AgentRecord> fnGetAgentModelFromHtml(String html)
			throws Exception {
		super.hasError(html);
		List<AgentRecord> records = fnGetAgentRecord(html);
		return records;
	}

	private List<AgentRecord> fnGetAgentRecord(String html) throws Exception {
		List<AgentRecord> records = new ArrayList<AgentRecord>();
		Document doc = Jsoup.parse(html, "UTF-8");
		Elements result = doc.select("tr");

		if (result.size() <= 0) {
			Log.e(TAG, "Error pattern found : No Result Table.");
			throw new Exception("Error response from server:\nNo result table.");
		}

		for (int i = 0; i < result.size(); i++) {
			// System.out.println(i + " ----------------");
			AgentRecord ar = new AgentRecord();
			Element e = result.get(i);
			Element ne = e.nextElementSibling();

			if (ne != null) {
				Elements children = ne.getAllElements();
				if (children.size() >= 11) {
					for (int j = 1; j < children.size(); j++) {
						Element c = children.get(j);
						// System.out.println("J: (" + j +
						// ") ---------------->"+c.html());
						// Element c = ele.nextElementSibling();
						if (c != null) {
							switch (j) {
							case 1:
								// System.out.println("Licence:" + c.html());
								ar.setLicence(c.html());
								break;
							case 2:
								ar.setName(c.html());
								// System.out.println("Name:" + c.html());
								break;
							case 4:
								ar.setIssue_date(c.html());
								// System.out.println("Issue Date:" + c.html());
								break;
							case 5:
								ar.setEnd_date(c.html());
								// System.out.println("End Date:" + c.html());
								break;
							case 11:
								ar.setExtra(c.html());
								// System.out.println("Extra:" + c.html());
								break;
							default:
								break;
							}
						}
					}
					records.add(ar);
				}
			}
		}
		return records;
	}
}
